package com.atxwq.shop.manager.serivce.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.atxwq.shop.manager.serivce.ValidateCodeService;
import com.atxwq.shop.model.vo.common.RedisCodeEnum;
import com.atxwq.shop.model.vo.system.ValidateCodeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Description 验证码服务层
 * @Date 2025/5/8 09:35
 * @Created by 12336
 */

@Service
@Slf4j
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Autowired
    private RedisTemplate<String , String> redisTemplate ;
    /**
     * 获取验证码
     * @return
     */
    @Override
    public ValidateCodeVo getValidateCode() {
        //1.生成图片验证码 参数：宽  高  验证码位数 干扰线数量
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 50, 4, 10);
        String code = circleCaptcha.getCode();
        String imageBase64 = circleCaptcha.getImageBase64();
        log.info("生成的验证码为："+ code);

        //2.生成key
        String codekey = UUID.randomUUID().toString().replace("-", "");

        //3.将图片验证码保存到redis中,设置过期时间5分钟
        redisTemplate.opsForValue().set(RedisCodeEnum.USER_LOGIN_CODE + codekey, code , 5 , TimeUnit.MINUTES);

        //4.构建响应结果数据
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(codekey);
        validateCodeVo.setCodeValue("data:image/png;base64," + imageBase64);

        //5.返回结果
        return validateCodeVo;
    }
}
